package boot;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

/**
 * When using Servlet 3.x, there is no equivalent of the welcome page you get
 * with a servlet application configured using web.xml. This is a convenience
 * filter for the Spring Boot examples in this course that mimics this behavior
 * and redirects to a specified home page.
 * <p>
 * A typical servlet URL used on this course is
 * <code>http://locahost:8080/lab-name/admin/accounts</code> where "lab-name" is
 * the context path and "admin" is the servlet path. If running Spring Boot,
 * entering the URLs <code>http://locahost:8080/lab-name</code> or
 * <code>http://locahost:8080/lab-name/admin</code> would normally result in a
 * 404. If running as a Servlet 2.x WAR application using web.xml,
 * <code>src/main/webapp/index.jsp</code> (in our case) is picked up as the
 * welcome page.
 * <p>
 * This filter spots these URLs and redirects to the home page passed to the
 * constructor, avoiding the 404 error.
 */
public class RedirectRootUrlsToHomeFilter implements Filter {

	protected String contextPath;
	protected String contextPathPlusSlash;
	protected String fullServletPath;
	protected String fullServletPathPlusSlash;
	protected String homeUrl;

	public RedirectRootUrlsToHomeFilter(String homePage) {

		if (!StringUtils.hasText(homePage))
			homePage = "/home";
		else if (homePage.charAt(0) != '/')
			homePage = '/' + homePage;

		Properties properties = new Properties();
		try {
			properties.load(new ClassPathResource("application.properties")
					.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String servletPath = properties.getProperty("server.servlet-path");
		contextPath = properties.getProperty("server.context-path");
		contextPathPlusSlash = contextPath + '/';
		homeUrl = servletPath + "/" + homePage; // Context relative

		// Match with or without trailing slash
		fullServletPath = contextPath + servletPath;
		fullServletPathPlusSlash = fullServletPath + '/';
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// Nothing to do
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String url = ((HttpServletRequest) request).getRequestURI();

		// Matches /lab-name, /lab-name/, /admin and /admin/ and
		// redirects them all to the home page
		if (url.equals(contextPath) || url.equals(contextPathPlusSlash)
				|| url.equals(fullServletPath)
				|| url.equals(fullServletPathPlusSlash)) {
			url = homeUrl;
			request.getRequestDispatcher(url).forward(request, response);
		} else {
			chain.doFilter(request, response);
		}

		return;
	}

	@Override
	public void destroy() {
		// Nothing to do
	}
}
